package com.forever.base.interceptors;

import java.util.Iterator;
import java.util.Map.Entry;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;

import com.forever.base.datasource.DataSourceContextHolder;
import com.forever.base.datasource.DataSourceKeys;

/**
 * 通过方法名拦截器,获得当前线程的datasource key
 */
public class DataSourceInterceptor implements MethodInterceptor {

	private DataSourceKeys dataSourceKeys;

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		try {
			String method = mi.getMethod().getName();
			if (StringUtils.isNotBlank(method)) {
				Iterator<Entry<String, String>> it = dataSourceKeys.getKeyMap().entrySet().iterator();
				while (it.hasNext()) {
					Entry<String, String> entry = it.next();
					String key = entry.getKey();
					String value = entry.getValue();
					if (method.startsWith(key)) {
						DataSourceContextHolder.setCustomerType(value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mi.proceed();
	}

	public DataSourceKeys getDataSourceKeys() {
		return dataSourceKeys;
	}

	public void setDataSourceKeys(DataSourceKeys dataSourceKeys) {
		this.dataSourceKeys = dataSourceKeys;
	}
}